
# infrared Obstacle Avoidance Sensor 
import RPi.GPIO as GPIO
import time
from .motor import *
from .led import *
import tm1637

class Infrared_Tracking:
	def __init__(self):
		self.Left_Sensor = 19 # Pin 35
		self.Right_Sensor = 4 # Pin 7
		GPIO.setup(self.Left_Sensor, GPIO.IN, pull_up_down=GPIO.PUD_UP)
		GPIO.setup(self.Right_Sensor, GPIO.IN, pull_up_down=GPIO.PUD_UP)
		self.Detected_Left_Barrier=0
		self.Detected_Right_Barrier=0
		self.Detected_Barrier=0

	def detected_barrier(self):
		if (0 == GPIO.input(self.Left_Sensor)):	#当检测到障碍物时，输出低电平信号
			self.Detected_Left_Barrier=1
			self.Detected_Barrier=1
		else: 
		    self.Detected_Left_Barrier=0
		
		if (0 == GPIO.input(self.Right_Sensor)):	#当检测到障碍物时，输出低电平信号
			self.Detected_Right_Barrier=1
			self.Detected_Barrier=1
		else:
			self.Detected_Right_Barrier=0
		if (self.Detected_Right_Barrier==0 and self.Detected_Left_Barrier==0):
			self.Detected_Barrier=0
			
	def destroy(self):
  	    GPIO.cleanup()                     # Release resource

	def worker(self,motor,led,tm):
		"""thread worker function"""
		while True:
			time.sleep(0.01)
			self.detected_barrier()
			# display
			if (self.Detected_Barrier==1):
				tm.show('0000', True)
           
			# print ("Measured Distance = %.1f cm" % dist)
			if (motor.MOTOR_STATE == Motor.GO or motor.MOTOR_STATE == Motor.LEFT or motor.MOTOR_STATE == Motor.RIGHT):
				if (self.Detected_Barrier==1):
					led.stop()
					motor.action(Motor.STOP)
					time.sleep(0.1)
					motor.action(Motor.BACK)
					time.sleep(0.3)
					motor.action(Motor.STOP)


if __name__ == '__main__':     # Program start from here
	GPIO.setmode(GPIO.BCM)  
	IRroas=Infrared_Obstacle_Sensor()
	try:
		while True:
			IRroas.detected_barrier()
			if (IRroas.Detected_Left_Barrier==1):
				print("Detected Left Barrier!")
			else:
			    pass #print("****Left Nothing!******")
		    
			if (IRroas.Detected_Right_Barrier==1):
				print("Detected Right Barrier!")
			else:
			    pass #print("****Right Nothing!******")
	except KeyboardInterrupt: 
		IRroas.destroy()


